﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Data;
using Newtonsoft.Json.Linq;
using Model;
using System.Web.Security;
using Core;
using Utils;

namespace Web.Controllers
{
    [AllowAnonymous]
    public class LoginController : Controller
    {
        //
        // GET: /Login/

        public ActionResult Index() {
            return View();
        }

        [HttpPost]
        public JsonResult DoAction(JObject request) {
            var userCode = request.Value<string>("user_code");
            var password = request.Value<string>("password");

            FormsAuthentication.SignOut();
            //if (Session["user_code"] == null)
            //   Session["user_code"] = userCode;
            //Session["user"] = null;

            if (string.IsNullOrEmpty(userCode))
                return Json(new { status = "error", message = "User Name must be type in!" });

            var service = new sys_userService();
            var model = service.GetModel(ParamQuery.Instance()
                                .AddWhere("user_code", userCode)
                                .AddWhere("password", Md5Hash.GetMd5Hash(password + "")));


            if (model == null || string.IsNullOrEmpty(model.user_code))
                return Json(new { status = "error", message = "User Name or Passowrd is incorrent!" + Session["user_code"] });


            FormsAuthentication.SetAuthCookie(model.user_id + "", false);
            //Session["user"] = model;

            return Json(new { status = "success", message = "Login succeed!" + request.Value<string>("user_code") }, JsonRequestBehavior.DenyGet);
        }

    }
}
